/*
 * Copyright 2015 MingxingWang

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.audaque.graphdb.util

import java.io.{DataInputStream, DataOutputStream}

import com.audaque.graphdb.{Edge, Property, SchemaFactory, Vertex}

/**
 * Created by Ming on 2015/3/30.
 */
object GraphDBUtil {
  def saveEdge(e: Edge, out: DataOutputStream) {
    out.writeLong(e.srcId)
    out.writeLong(e.dstId)
    if (e.prop == null || e.prop.schema == null) {
      out.writeLong(-1)
    } else {
      out.writeLong(e.prop.schema.id)
      e.prop.save(out)
    }
  }

  def loadEdge(in: DataInputStream, schFact: SchemaFactory): Edge = {
    try {
      val srcId = in.readLong()
      val dstId = in.readLong()
      val schId = in.readLong()
      if (schId >= 0) {
        schFact.getSchemaById(schId) match {
          case Some(sch) =>
            val prop = Property(sch).load(in)
            Edge(srcId, dstId, prop)
          case None => Edge(srcId, dstId)
        }
      } else {
        Edge(srcId, dstId)
      }
    } catch {
      case _: Throwable => null
    }
  }

  def saveVertex(v: Vertex, out: DataOutputStream) = {
    out.writeLong(v.vid)
    if (v.prop == null || v.prop.schema == null) {
      out.writeLong(-1)
    } else {
      out.writeLong(v.prop.schema.id)
      v.prop.save(out)
    }
  }

  def loadVertex(in: DataInputStream, schFact: SchemaFactory): Vertex = {
    try {
      val vid: Long = in.readLong()
      val schId = in.readLong()
      if (schId >= 0) {
        schFact.getSchemaById(schId) match {
          case Some(sch) =>
            val prop = Property(sch).load(in)
            Vertex(vid, prop)
          case None => Vertex(vid, null)
        }
      } else {
        Vertex(vid, null)
      }
    } catch {
      case _: Throwable => null
    }
  }
}
